const express = require("express");
const swig = require("swig");
const mongoose = require("mongoose");
const cookies = require("cookies");

const apiRouter = require("./routers/apiRouter");
const htmlRouter = require("./routers/htmlRouter")


new Promise((resolve,reject)=>{
    mongoose.connect("mongodb://localhost:27021",(error)=>{
        if(!error){
            console.log("数据库连接成功");
            resolve()
        }else{
            console.log("数据库连接失败");
        }
    })
})
.then(()=>{
    const server = express();

    //处理静态资源文件
    server.use("/static",express.static(__dirname+"/public"));

    //处理cookies(没有第一个参数，不过滤)
    server.use((request,response,next)=>{
        //创建一个cookies对象(传入request,response)
        let cookie = new cookies(request,response);
        /*
        //设置cookie
        cookie.set("key","12341234");
        //获取cookie的value值
        let value = cookie.get("key");
        */

        //拓展request||response对象，next()传出cookie
        response.cookie = cookie;
        
        next();
    })

    //处理ajax
    server.use("/api",apiRouter);

    //处理html
    server.engine("html",swig.renderFile);
    server.set("views",__dirname+"/html");
    server.set("view engine","html");
    swig.setDefaults({cache:false});

    server.use("/",htmlRouter);

    server.listen(8080,"localhost",(error)=>{
        if(!error){
            console.log("服务器启动成功");
        }else{
            console.log("服务器启动失败");
        }
    })
})